/**
 * 
 */
package bi.uc.pay;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import com.bi_uc.www.R;

import bi.uc.client.AddMoneyActivity;
import bi.uc.client.ExitApplication;
import bi.uc.login.Info;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Administrator
 *
 */
public class GuestActivity extends Activity implements Runnable {
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	Info info = Info.getInfo();
	EditText needPay;
	TextView payMoney;
	TextView result;	
	EditText cash;		
	public HashMap<String, HashMap<String, String>> goodsInfo;
	public ArrayList<HashMap<String, String>> source;
	
	String json;
	String sellinfo;
	double sellByPrice = 0;
	double sellSum = 0;
	double returnMoney = 0;
	double hasPayMoney = 0;
	double needmoney = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.guestactivity);
		goodsInfo = (HashMap<String, HashMap<String, String>>) getIntent().getSerializableExtra("goodsInfo");
		source = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("source");		
		Log.d("goodsInfo:"+goodsInfo.size(), "source:"+source.size());
		needPay = (EditText) findViewById(R.id.needpay);
		payMoney = (TextView) findViewById(R.id.paymoney);
		result = (TextView) findViewById(R.id.result);		
		cash = (EditText) findViewById(R.id.cash);
		data();
		needPay.setText(info.subZeroAndDot(Math.round((sellByPrice+sellSum*info.storeDiscount)*100)/100.0+""));
		needPay.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (info.isChangeNeedPay) {					
					needPay.setFocusableInTouchMode(true);
				} else {
					needPay.setFocusableInTouchMode(false);					
				}
				return false;
			}
		});
		needPay.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0'){
					needPay.setText(s.toString().substring(1));
					info.setSpan(needPay);
					return;
				}
				if (s.length() < 1) {
					needPay.setText("0");
					info.setSpan(needPay);
					return;
				}
				if (".".equals(s.toString())) {
					needPay.setText("0.");
					info.setSpan(needPay);
					return;
				}
			}
		});
		cash.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0'){
					cash.setText(s.toString().substring(1));
					info.setSpan(cash);
					return;
				}
				if (s.length() < 1) {
					cash.setText("0");
					info.setSpan(cash);
					return;
				}
				if (".".equals(s.toString())) {
					cash.setText("0.");
					info.setSpan(cash);
					return;
				}				
				needmoney = Double.parseDouble(needPay.getText().toString());						
				hasPayMoney = Double.parseDouble(s.toString());
				returnMoney = hasPayMoney - needmoney;
				payMoney.setText(info.subZeroAndDot(""+hasPayMoney)+"元");
				if (returnMoney>0.0000001) {
					result.setText("找零"+info.subZeroAndDot(returnMoney+"")+"元");
				} else if (Math.abs(returnMoney)<0.0000001) {
					result.setText("结清");
				} else {
					result.setText("少付"+info.subZeroAndDot(-returnMoney+"")+"元");
				}
			}
		});
				
	}
	

	private void data(){
		// TODO Auto-generated method stub
		JSONArray jsonArray = new JSONArray();
		try {
			json = writeJSON(jsonArray);
			sellinfo = writeXml(jsonArray);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	/**
	 * 
	 */
	private void send()  throws Exception{
		// TODO Auto-generated method stub
		String Url = "http://bi.bi-uc.com/BI.api";
		HttpPost httpRequest = new HttpPost(Url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-储值消费");
		NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);	
		String s;
		if (returnMoney<0.0000001) {
			s = "0";
		} else {
			s = Math.round(returnMoney*100)/100.0+"";
		}
		NameValuePair pair3 = new BasicNameValuePair("找零金额", info.subZeroAndDot(s));
		NameValuePair pair4 = new BasicNameValuePair("店面", info.shopID);
		needmoney = Double.parseDouble(needPay.getText().toString());
		NameValuePair pair5 = new BasicNameValuePair("应付金额", info.subZeroAndDot(Math.round(needmoney*100)/100.0+""));
		NameValuePair pair6 = new BasicNameValuePair("实付金额", info.subZeroAndDot(Math.round(hasPayMoney*100)/100.0+""));
		NameValuePair pair7 = new BasicNameValuePair("现金支付", info.subZeroAndDot(Math.round(hasPayMoney*100)/100.0+""));
		String sellByDiscount = Math.round(100*sellSum*(info.isChangeNeedPay?info.storeDiscount:1))/100.0+"";
		NameValuePair pair8 = new BasicNameValuePair("支付总额", info.subZeroAndDot(sellByDiscount));
		NameValuePair pair9 = new BasicNameValuePair("支付总额原价出售", info.subZeroAndDot(Math.round(100*sellByPrice)/100.0+""));
		NameValuePair pair10 = new BasicNameValuePair("操作员", info.userID);
		NameValuePair pair11 = new BasicNameValuePair("店面折扣", info.subZeroAndDot(info.storeDiscount+""));
		NameValuePair pair12 = new BasicNameValuePair("消费记录", json);
		NameValuePair pair13 = new BasicNameValuePair("储值消费明细", sellinfo);
				
		params.add(pair1);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);
		params.add(pair5);
		params.add(pair6);
		params.add(pair7);
		params.add(pair8);
		params.add(pair9);
		params.add(pair10);
		params.add(pair11);
		params.add(pair12);
		params.add(pair13);
		HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(httpRequest);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			/*InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
			StringBuffer responseMessage = new StringBuffer();
			int charCount = -1;  
			   while ((charCount = br.read()) != -1) {  
				    responseMessage.append((char) charCount);  
				   }  
			   Log.d("tag", responseMessage.toString());*/
			InputStream in = response.getEntity().getContent();// 接收服务器的数据
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();    // 获取XmlPullParser的实例					
			final XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(in,
					"UTF-8");
			parser.setInput(responseReader);
			parser.next();
			int eventType = parser.getEventType();
			if (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals("XML")) { // String result = parser.getAttributeValue(0);
					String result = parser.getAttributeValue(null, "EXEC");
					if (result.equals("True")) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Intent intent = getIntent();						 
								/* 将数据打包到aintent Bundle 的过程略 */
								setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
								finish();
							}
						});
						
					} else {

						final String error = parser.getAttributeValue(null,
								"错误消息");

						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Toast.makeText(GuestActivity.this,
										"散客消费失败！" + error, Toast.LENGTH_SHORT)
										.show();
							}
						});
						
					}
				}
			}
			in.close();
		
			responseReader.close();
		}
		else
		{
			runOnUiThread(new Runnable() {				
				@Override
				public void run() {
					Toast.makeText(GuestActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
					}
			});	
		}		
		
	}

	private String writeJSON(JSONArray jsonArray) throws Exception{
		for (HashMap<String, String> value : source) {
			JSONObject jsonObject = new JSONObject(value);
			HashMap<String, String> map = goodsInfo.get(value.get("条码"));
			jsonObject.put("pItem_Name", value.get("商品"));
			jsonObject.put("pItem_Id", map.get("pItem_Id"));
			jsonObject.put("pItem_Barcode", value.get("条码"));
			jsonObject.put("pItem_SellingPrice", value.get("单价"));
			jsonObject.put("pItem_DiscountRate", map.get("pItem_DiscountRate"));
			jsonObject.put("pItem_IntegralRate", map.get("pItem_IntegralRate"));
			jsonObject.put("储值消费明细_会员日折扣", 1);
			jsonObject.put("储值消费明细_会员日积分", 1);
			Double money;
			if ("1".equals(map.get("pItem_IsSellByPrice"))) {
				money = Double.parseDouble(value.get("总价"));
				sellByPrice += money;
			}else{
				money = Double.parseDouble(value.get("总价"))*(info.isGoodsDiscount?Double.parseDouble(map.get("pItem_DiscountRate")):1);
				sellSum += money;
			}
			jsonObject.put("Payment", info.subZeroAndDot(money+""));
			jsonObject.put("Integral", 0);
			jsonObject.put("Consume_Number", Integer.parseInt(value.get("数量")));
			jsonObject.put("pItem_IsSellByPrice", Integer.parseInt(map.get("pItem_IsSellByPrice")));
			jsonObject.put("is_leaf", true);
			jsonArray.put(jsonObject);
		}
		return Base64.encodeToString(jsonArray.toString().getBytes(),Base64.DEFAULT);
	}

	private String writeXml(JSONArray jsonArray) throws Exception {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		serializer.setOutput(writer);
		// <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
//		serializer.startDocument("UTF-8", true);
		// <储值消费明细>
		serializer.startTag("", "储值消费明细");
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsob = jsonArray.getJSONObject(i);
			// <行记录 ...>
			serializer.startTag("", "行记录");
			serializer.attribute("", "储值消费明细_商品", jsob.getString("pItem_Id"));
			serializer.attribute("", "储值消费明细_商品名称",
					jsob.getString("pItem_Name"));
			serializer.attribute("", "储值消费明细_商品售价",
					jsob.getString("pItem_SellingPrice"));
			serializer.attribute("", "储值消费明细_折扣系数",
					jsob.getString("pItem_DiscountRate"));
			serializer.attribute("", "储值消费明细_积分系数",
					jsob.getString("pItem_IntegralRate"));
			serializer.attribute("", "储值消费明细_会员日折扣", "1");
			serializer.attribute("", "储值消费明细_会员日积分", "1");
			serializer.attribute("", "储值消费明细_是否以原价销售",
					jsob.getString("pItem_IsSellByPrice"));
			serializer.attribute("", "储值消费明细_套餐", "0");
			serializer.attribute("", "储值消费明细_套餐名称", "");
			serializer.attribute("", "储值消费明细_备注", "");
			serializer.attribute("", "数量", jsob.getString("Consume_Number"));
			serializer.attribute("", "商品名称", jsob.getString("pItem_Name"));
			serializer
					.attribute("", "售价", jsob.getString("pItem_SellingPrice"));
			serializer
					.attribute("", "折扣", jsob.getString("pItem_DiscountRate"));
			serializer.attribute("", "金额", jsob.getString("Payment"));
			serializer.endTag("", "行记录");
		}
		serializer.startTag("", "提成人");
		serializer.endTag("", "提成人");
		serializer.endTag("", "储值消费明细");
		serializer.endDocument();
		Log.d("tag", "结果："+writer.toString());
		return Base64.encodeToString(writer.toString().getBytes(),
				Base64.DEFAULT);

	}
	
	
	public void onClick(View view) {
		if (info.stopFlag) {
			Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
					.show();
		} else {
			new Thread(this).start();
		}
	}


	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			send();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
